package com.ruoyi.good.service;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.good.model.entity.GoodSkuEntity;
import com.ruoyi.good.model.vo.GoodSkuStockKeyVO;
import com.ruoyi.good.repository.IActivityRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * TODO
 *
 * @Description
 * @Author wkm
 * @Date 2024/12/29
 **/
@Slf4j
@Service
public class ActivityService implements ISkuStock {

    @Resource
    private IActivityRepository activityRepository;


    @Override
    public boolean assembleGoodSku(Long goodsId) {
        GoodSkuEntity goodSkuEntity = activityRepository.queryGoodSku(goodsId);
        cacheGoodSkuStockCount(goodsId, goodSkuEntity.getStockCountSurplus());
        return true;
    }

    @Override
    public GoodSkuStockKeyVO takeQueueValue() throws InterruptedException {
        return activityRepository.takeQueueValue();
    }

    @Override
    public void clearQueueValue() {
        activityRepository.clearQueueValue();
    }

    @Override
    public void updateGoodSkuStock(Long goodsId) {
        activityRepository.updateGoodSkuStock(goodsId);
    }

    @Override
    public void clearGoodSkuStock(Long goodsId) {
        activityRepository.clearGoodSkuStock(goodsId);
    }

    private void cacheGoodSkuStockCount(Long sku, Integer stockCount) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        activityRepository.cacheGoodSkuStockCount(cacheKey, stockCount);
    }

    @Override
    public boolean subtractionGoodSkuStock(Long goodsId, Date endDateTime) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + goodsId;
        return activityRepository.subtractionGoodSkuStock(goodsId, cacheKey, endDateTime);
    }

    @Override
    public boolean action(Long goodsId) {
        boolean status = subtractionGoodSkuStock(goodsId, new Date(100000000));
        // true；库存扣减成功
        if (status) {
            log.info("商品库存处理【库存】成功 goodsId:{}", goodsId);

            // 写入延迟队列，延迟消费更新库存记录
            activityRepository.goodSkuStockConsumeSendQueue(GoodSkuStockKeyVO.builder()
                    .goodsId(goodsId)
                    .build());
        }
        return true;
    }
}
